<template>
  <transition name="mask">
    <div v-show="videoShow" class="video-player-wrapper" @click.self="handleClose">
      <video
        :id="'player-' + element.id"
        :ref="'player-' + element.id"
        class="video"
        :loop="pOption.loop"
        :controls="inScreen"
        autoplay
        muted
      />
      <div v-if="editMode === 'edit'" class="stream-mask edit-mask-stream" />
      <div v-if="mobileLayoutStatus" class="stream-mask">
        <span style="opacity: 0.7">
          <span style="color: lightgray">{{ $t('panel.stream_mobile_tips') }}</span>
        </span>
      </div>
    </div>
  </transition>
</template>

<script>
import { mapState } from 'vuex'
import bus from '@/utils/bus'
import flvjs from 'flv.js'
import videoJs from 'video.js'
import 'video.js/dist/video-js.css'

export default {
  name: 'Index',
  props: {},
  data() {
    return {
      flvPlayer: null,
      hlsPlayer: null,
      // element: {
      //   id: '111',
      //   streamMediaLinks: {
      //     videoType: 'flv',
      //     flv: {
      //       type: 'flv',
      //       isLive: true,
      //       cors: true,
      //       loop: true,
      //       autoplay: false,
      //       url: 'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-720p.flv',
      //       segments: [
      //         {
      //           url: 'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-720p.flv',
      //           timestampBase: 0,
      //           cors: true,
      //           withCredentials: false,
      //         },
      //       ],
      //       withCredentials: false,
      //     },
      //     hls: {
      //       type: 'hls',
      //       isLive: true,
      //       cors: true,
      //       loop: true,
      //       autoplay: false,
      //       url: null,
      //     },
      //   },
      // },
    }
  },
  computed: {
    pOption() {
      return this.element?.streamMediaLinks?.[this.videoType] ?? {}
    },
    videoType() {
      return this.element?.streamMediaLinks?.videoType ?? 'flv'
    },
    url() {
      return this.pOption?.url ?? ''
    },
    imageAdapter() {
      const style = {
        position: 'relative',
        width: '100%',
        height: '100%',
      }
      if (this.element.style.adaptation === 'original') {
        style.width = 'auto'
        style.height = 'auto'
      } else if (this.element.style.adaptation === 'equiratio') {
        style.height = 'auto'
      }
      return style
    },
    moveFlag() {
      return this.element.optStatus.dragging || this.element.optStatus.resizing
    },
    curGap() {
      return this.element.auxiliaryMatrix ? this.componentGap : 0
    },
    player() {
      return this.$refs.videoPlayer.player
    },
    ...mapState(['mobileLayoutStatus', 'videoShow', 'element']),
  },
  watch: {
    // pOption: {
    //   handler: function () {
    //     this.initOption()
    //   },
    //   deep: true,
    // },
    videoShow() {
      if (this.videoShow) {
        this.$nextTick(() => {
          this.initOption()
        })
      }
    },
  },
  mounted() {
    // console.log(this.url)
    // bus.$on('streamMediaLinksChange-' + this.element.id, this.streamMediaLinksChange)
  },
  beforeDestroy() {
    // bus.$off('streamMediaLinksChange-' + this.element.id, this.streamMediaLinksChange)
    this.destroyPlayer()
  },
  methods: {
    streamMediaLinksChange() {
      this.pOption = this.element.streamMediaLinks[this.videoType]
      this.flvPlayer = null
      this.videoShow = false
      this.$nextTick(() => {
        this.videoShow = true
        this.initOption()
      })
    },
    initOption() {
      if (!this.url) return
      if (this.videoType === 'flv') {
        this.initFlv()
      } else if (this.videoType === 'hls') {
        this.initHls()
      } else if (this.videoType === 'monitor') {
        this.initHls()
      }
    },
    initFlv() {
      if (flvjs.isSupported()) {
        this.destroyPlayer()
        const video = this.$refs['player-' + this.element.id]
        if (video) {
          try {
            this.flvPlayer = flvjs.createPlayer(this.pOption, {
              enableWorker: false, // 不启用分离线程
              enableStashBuffer: false, // 关闭IO隐藏缓冲区
              isLive: this.pOption.isLive,
              lazyLoad: false,
            })
            this.flvPlayer.attachMediaElement(video)
            this.flvPlayer.load()
            this.flvPlayer.play()
          } catch (error) {
            console.error('flvjs err ignore', error)
          }
        }
      }
    },
    initHls() {
      this.destroyPlayer()
      const video = this.$refs['player-' + this.element.id]
      if (video) {
        this.hlsPlayer = videoJs(
          video,
          {
            autoplay: true,
            controls: false,
            loop: true,
            poster: '',
            muted: true,
            preload: 'auto',
            sources: [
              {
                src: this.url,
              },
            ],
          },
          function onPlayerReady() {
            console.log('onPlayerReady', this)
          }
        )
      }
    },
    destroyPlayer() {
      // Destroy
      if (this.flvPlayer) {
        this.flvPlayer.pause()
        this.flvPlayer.destroy()
        this.flvPlayer = null
      }
      if (this.hlsPlayer) {
        this.hlsPlayer.pause()
        this.hlsPlayer.dispose()
        this.hlsPlayer = null
      }
    },
    handleClose() {
      this.$store.commit('SET_VIDEO_SHOW', false)
      this.$store.commit('SET_ELEMENT', {})
    },
  },
}
</script>

<style lang="scss" scoped>
.video-player-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999999;
  background-color: rgba(0, 0, 0, 0.5);
}
.mask-enter-active,
.mask-leave-active {
  transition: opacity 0.5s;
}
.mask-enter,
.mask-leave-to {
  opacity: 0;
}
.video {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
}
</style>
